package com.easemob.chatuidemo.http;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by base on 2016/6/22.
 */
public class HttpMethods {
    private static final String BASE_URL = "http://192.168.20.245:80/MIData_server/";
    private static final int DEFAULT_TIMEOUT = 5;
    private final Retrofit retrofit;
    private ApiService apiService;
    //成功返回码
    private static final String RETURN_CODE = "0000";


    public HttpMethods() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();

        apiService = retrofit.create(ApiService.class);
    }


    private static class SingletonHolder{
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    public static HttpMethods getInstance(){
        return SingletonHolder.INSTANCE;
    }


    public void getMovie(Subscriber<MiResponse> subscriber, MiEntity miEntity){
        apiService.getTopMovie(miEntity.getCommond(),miEntity.getReqMessageBody())
                .map(new HttpResultFunc<MiResponse>())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    private class HttpResultFunc<T> implements Func1<HttpResult<T>,T>{

        @Override
        public T call(HttpResult<T> tHttpResult) {
            if(!tHttpResult.getResultCode().equals(RETURN_CODE)){
                throw new ApiException(tHttpResult.getResultCode());
            }
            return tHttpResult.getData();
        }
    }

}
